package cn.admin.configcenter.registry.service.client;

import cn.admin.configcenter.registry.common.config.ConfigSetting;
import cn.admin.remoting.Connection;
import cn.admin.remoting.IOEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class IncomingConnectionListener implements
        IOEventListener.ConnectionLifecycleListener {

    private static final Logger LOG = LoggerFactory.getLogger(IncomingConnectionListener.class);

    @Override
    public void connectionOpened(Connection conn) {
        LOG.info("[Connected] " + conn);
        int nativeConns = ClientConnectionWorker.allNativeClients.size();
        if (nativeConns >= ConfigSetting.maxClientConnections && ConfigSetting.ignoreClientConnectionsOverflow) {
            conn.close(conn + "" + ConfigSetting.maxClientConnections);
            LOG.info("[fire-close-connection] close {} when connection overload",
                    conn);
        }
    }

    @Override
    public void connectionClosed(Connection connection) {
        normalConnClosed(connection);
    }

    private void normalConnClosed(Connection conn) {
        ClientConnectionWorkers.dispatch(conn.getRemoteAddress(), new ClientDisconnectJob(conn));
    }
}
